<?php

namespace App\Listeners\OpenShop;

use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Events\OpenShop\SignToPositionTimeEvent;
use App\Listeners\BaseListener;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopStatisticsModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use Carbon\Carbon;

class SignToPositionTimeListener extends BaseListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Handle the event.
     *
     * @param SignToPositionTimeEvent $event
     * @return void
     */
    public function handle(SignToPositionTimeEvent $event)
    {
        $siteMissionModel = OpenShopSiteMissionModel::query()
            ->where('mainStep', MainProcessEnum::MAIN_PROCESS_SHOP_LOCATION)
            ->where('stepStatus', MissionTemplateEnum::STEP_STATUS_5)
            ->where('orderNo', $event->orderNo)
            ->first();

        if ($siteMissionModel == null) {
            return;
        }

        // 判断订单状态
        $signOrderModel = OpenShopSignOrderModel::query()
            ->where('orderNo', $siteMissionModel->orderNo)
            ->first();

        // 过滤作废订单
        if ($signOrderModel == null) {
            return;
        }

        if ($signOrderModel->status == SignOrderEnum::ORDER_STATUS_NO) {
            return;
        }

        if ($signOrderModel->shopCode == 0) {
            return;
        }

        // 签约时间
        $signTime = (int)OpenShopUserContractModel::query()
            ->where('orderNo', $siteMissionModel->orderNo)
            ->value('signTime');


        // 落址时间
        $positionTime = $siteMissionModel->completeAt;

        if (!$signTime || !$positionTime) {
            return;
        }

        try {
            // 统计时长
            $diffDays = Carbon::createFromTimestamp($signTime)->diffInDays(Carbon::createFromTimestamp($positionTime));
        } catch (\Exception $exception) {
            return;
        }

        OpenShopStatisticsModel::query()
            ->updateOrCreate([
                'orderNo' => $event->orderNo,
            ], [
                'type'        => OpenShopStatisticsModel::TYPE_TIME,
                'orderNo'     => $event->orderNo,
                'statistics'  => '落位时长',
                'beforeValue' => $signTime,
                'nowValue'    => $positionTime,
                'addition'    => $diffDays,
                'updatedAt'   => time(),
            ]);
    }
}
